package nccloud.web.platform.workbench.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import nc.bs.framework.common.RuntimeEnv;
import nc.bs.logging.Logger;
import nc.bs.sec.esapi.NCESAPI;
import nc.itf.org.IGroupQryService;
import nc.itf.uap.ml.ICloudMultiLang;
import nc.sfbase.yht.itf.IYhtServiceProvider;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.org.GroupVO;
import nc.vo.platform.workbench.AppPageVO;
import nc.vo.platform.workbench.AppParamVO;
import nc.vo.platform.workbench.AppRegisterVO;
import nc.vo.platform.workbench.model.AppOpenAggVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.sm.UserRefreshTokenVO;
import nccloud.commons.lang.StringUtils;
import nccloud.core.baseapp.YhtLoginUtil;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.ClientInfo;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.framework.web.json.JsonFactory;
import nccloud.impl.platform.common.util.ArrayUtils;
import nccloud.impl.platform.db.processor.NCCloudServiceFactory;
import nccloud.pubitf.baseapp.apprbac.IAppAndOrgPermQueryPubService;
import nccloud.pubitf.baseapp.oauth.IUserRefreshTokenService;
import nccloud.pubitf.graphic.service.IGraphicReportLicenseService;
import nccloud.pubitf.platform.workbench.IAppPage;
import nccloud.pubitf.platform.workbench.IAppParam;
import nccloud.pubitf.platform.workbench.IAppRegister;
import nccloud.pubitf.platform.workbench.IDoFunPropService;
import nccloud.pubitf.platform.workbench.IExtCloudService;
import nccloud.pubitf.riart.riasfbase.appchk.IOpenAppCheckService;
import nccloud.riart.bean.appchk.AttachedRequest;
import nccloud.riart.bean.appchk.AttachedResponse;
import nccloud.web.baseapp.yht.action.YhtUtil;
import nccloud.web.platform.workbench.util.OpenAppUtil;

public class OpenAppAction implements ICommonAction {
	public Object doAction(IRequest request) {
		IJson json = JsonFactory.create();
		String read = request.read();
		Map paramMap = (Map) json.fromJson(read, Map.class);
		AppOpenAggVO appOpenAggVO = new AppOpenAggVO();
		String appcode = (String) paramMap.get("appcode");
		appcode = NCESAPI.sqlEncode(appcode);
		String menucode = (String) paramMap.get("menucode");
		String pagecode = (String) paramMap.get("pagecode");
		boolean is_cloud_app = false;
		if (paramMap.get("is_cloud_app") != null) {
			is_cloud_app = (Boolean) paramMap.get("is_cloud_app");
		}

		ClientInfo clientInfo = SessionContext.getInstance().getClientInfo();
		if (is_cloud_app) {
			this.openCloudApp(appOpenAggVO, appcode);
			return appOpenAggVO;
		} else {
			String pk_group = clientInfo.getPk_group();
			String userId = clientInfo.getUserid();
			IAppRegister service = (IAppRegister) ServiceLocator.find(IAppRegister.class);
			boolean is_haspower = true;
			String[] needFields = new String[]{"pk_appregister", "name", "own_module", "source_app_code", "resid",
					"image_src", "fun_property"};
			AppRegisterVO appRegisterVO = ((IAppRegister) ServiceLocator.find(IAppRegister.class))
					.queryAppVOByCode(appcode, needFields, true);
			if (appRegisterVO == null) {
				appOpenAggVO.setIs_haspower(UFBoolean.valueOf(false));
				appOpenAggVO.setHint_message(
						NCLangRes4VoTransl.getNCLangRes().getStrByID("100001baseapp_0", "0100001baseapp-0138"));
				return appOpenAggVO;
			} else {
				int fun_property = appRegisterVO.getFun_property();
				String isHomeFrontStr;
				String pageUrl;
				AppParamVO[] parems;
				if (fun_property > 3) {
					IExtCloudService weservice = NCCloudServiceFactory.getInstance().getService(fun_property);
					IDoFunPropService funservice = (IDoFunPropService) ServiceLocator.find(IDoFunPropService.class);
					isHomeFrontStr = null;
					pageUrl = appRegisterVO.getPk_appregister();
					IAppParam paramService = (IAppParam) ServiceLocator.find(IAppParam.class);
					parems = paramService.queryAppParams(pageUrl);

					try {
						appOpenAggVO = service.openApp(appcode, pagecode, menucode);
						isHomeFrontStr = funservice.process_RequiresNew(parems, pageUrl, appcode, weservice);
						appOpenAggVO.setPageurl(isHomeFrontStr);
					} catch (BusinessException var28) {
						Logger.error(var28);
						ExceptionUtils.wrapBusinessException(var28.getMessage());
					}

					AppParamVO appparamvo = paramService.queryAppParamByAppCode(appcode, "is_menu");
					if (appparamvo != null && appparamvo.getParamvalue() != null
							&& "Y".equals(appparamvo.getParamvalue())) {
						appOpenAggVO.setIs_cloud_app(UFBoolean.TRUE);
					}

					appOpenAggVO.setIs_haspower(UFBoolean.TRUE);
					appOpenAggVO.setAppid(pageUrl);
					return appOpenAggVO;
				} else {
					try {
						int user_type = clientInfo.getUserType();
						if (2 != user_type && !"7012001ZSCK".equals(appcode)&& !"36020PSP".equals(appcode)) {
							is_haspower = ((IAppAndOrgPermQueryPubService) ServiceLocator
									.find(IAppAndOrgPermQueryPubService.class)).userHasPermOfAppcode(userId, appcode,
											pk_group);
							if (!is_haspower) {
								appOpenAggVO.setIs_haspower(UFBoolean.valueOf(is_haspower));
								appOpenAggVO.setHint_message(NCLangRes4VoTransl.getNCLangRes()
										.getStrByID("100001baseapp_0", "0100001baseapp-0139"));
								return appOpenAggVO;
							}
						}

						AttachedResponse reponse = this.openAppCheck(paramMap, request, appRegisterVO);
						if (!reponse.isSuccess()) {
							is_haspower = reponse.isSuccess();
							appOpenAggVO.setIs_haspower(UFBoolean.valueOf(is_haspower));
							appOpenAggVO.setHint_message(reponse.getResult());
							return appOpenAggVO;
						}

						appOpenAggVO = service.openApp(appcode, pagecode, menucode);
						appOpenAggVO.setAppid(appRegisterVO.getPk_appregister());
					} catch (BusinessException var30) {
						Logger.error(var30);
						ExceptionUtils.wrapBusinessException(var30.getMessage());
					}

					boolean isDevelopMode = RuntimeEnv.getInstance().isDevelopMode();
					boolean isHomeFront = false;
					isHomeFrontStr = System.getProperty("nc.HomeFront");
					if (!StringUtils.isEmpty(isHomeFrontStr)) {
						isHomeFront = Boolean.valueOf(isHomeFrontStr);
					}

					if (isDevelopMode && !isHomeFront) {
						pageUrl = appOpenAggVO.getPageurl();
						if (pageUrl != null && (pageUrl.indexOf("/nccloud/resources") > -1
								|| pageUrl.indexOf("../../../../") > -1)) {
							pageUrl = pageUrl.replace("/nccloud/resources", "");
							pageUrl = pageUrl.replace("../../../../", "/");
							appOpenAggVO.setPageurl(pageUrl);
						}
					}

					IAppParam paramService = (IAppParam) ServiceLocator.find(IAppParam.class);
					AppParamVO[] params = paramService.queryAppParamsByAppCode(appcode);
					if (params != null && params.length > 0) {
						parems = params;
						int var24 = params.length;

						for (int var25 = 0; var25 < var24; ++var25) {
							AppParamVO param = parems[var25];
							if ("is_menu".equals(param.getParamname()) && "Y".equals(param.getParamvalue().trim())) {
								appOpenAggVO.setIs_cloud_app(UFBoolean.TRUE);
							} else if (RuntimeEnv.getInstance().isRunningOnCloud()
									&& "systypecode".equals(param.getParamname())) {
								try {
									service.checkSystypeCode(param.getParamvalue().trim());
								} catch (BusinessException var29) {
									Logger.error(var29);
									ExceptionUtils.wrapBusinessException(var29.getMessage());
								}
							} else if ("sec_develop".equals(param.getParamname())
									&& "Y".equals(param.getParamvalue().trim())) {
								appOpenAggVO.setIs_sec_develop(UFBoolean.TRUE);
							}
						}
					}

					appOpenAggVO.setImage_src(appRegisterVO.getImage_src());
					String absolutePath = appOpenAggVO.getPageurl();
					String relativePath = null;
					if (StringUtils.isNotEmpty(absolutePath) && absolutePath.indexOf("/nccloud/resources/") > -1) {
						relativePath = absolutePath.replace("/nccloud/resources/", "../../../../");
					} else {
						relativePath = absolutePath;
					}

					appOpenAggVO.setPageurl(relativePath);
					return appOpenAggVO;
				}
			}
		}
	}

	private AttachedResponse openAppCheck(Map<String, String> paramMap, IRequest request, AppRegisterVO appRegisterVO)
			throws BusinessException {
		IGraphicReportLicenseService reportService = (IGraphicReportLicenseService) ServiceLocator
				.find(IGraphicReportLicenseService.class);
		reportService.checkReportLicense(appRegisterVO.getName(), (String) paramMap.get("appcode"));
		AttachedRequest attachedRequest = new AttachedRequest();
		attachedRequest.setAppcode((String) paramMap.get("appcode"));
		attachedRequest.setAppname(appRegisterVO.getName());
		attachedRequest.setLogindevice(1);
		attachedRequest.setLoginip(request.getClientIp());
		attachedRequest.setLogintype(7);
		attachedRequest.setOwnModule(appRegisterVO.getOwn_module());
		attachedRequest.setPk_app(appRegisterVO.getPk_appregister());
		attachedRequest.setSrcAppcode(appRegisterVO.getSource_app_code());
		attachedRequest.setSessionid(request.getSessionId());
		attachedRequest.setSysid(7);
		attachedRequest.setNeedcommoncheck(OpenAppUtil.RPBillLicenseCheck((String) paramMap.get("appcode")));
		IOpenAppCheckService checkService = (IOpenAppCheckService) ServiceLocator.find(IOpenAppCheckService.class);
		AttachedResponse reponse = checkService.unitedOpenNodeChk(attachedRequest);
		return reponse;
	}

	private void openCloudApp(AppOpenAggVO appOpenAggVO, String appCode) {
		appOpenAggVO.setIs_cloud_app(UFBoolean.TRUE);
		appOpenAggVO.setIs_haspower(UFBoolean.TRUE);
		IYhtServiceProvider provider = (IYhtServiceProvider) ServiceLocator.find(IYhtServiceProvider.class);
		String yhtUrl = provider.getProByKeyForYht("yht.url");
		String diworkUrl = provider.getProByKeyForYht("diwork.url");

		try {
			String encodeDiworkUrl = URLEncoder.encode(diworkUrl, "utf-8");
			String yhtLoginUrl = yhtUrl + "/cas/login?token=";
			String diworkLoginUrl = "&service=" + encodeDiworkUrl + "%2Flogin%3FtenantId%3D";
			String serviceUrl = "%26service%3D" + encodeDiworkUrl + "%252F%2523%252Fservice%252F";
			ClientInfo clientInfo = SessionContext.getInstance().getClientInfo();
			String userId = clientInfo.getUserid();
			String pk_group = clientInfo.getPk_group();
			long bizDateTime = clientInfo.getBizDateTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String transDate = sdf.format(new Date(bizDateTime));
			String langCode = ((ICloudMultiLang) ServiceLocator.find(ICloudMultiLang.class)).getCurrLocalCode();
			String paramUrl = "%26businessDate%3D" + transDate + "%26locale%3D" + langCode + "%26nccUserId%3D" + userId;
			GroupVO groupVO = ((IGroupQryService) ServiceLocator.find(IGroupQryService.class))
					.queryGroupVOByGroupID(pk_group);
			String tenantId = groupVO.getTenantid();
			IUserRefreshTokenService userRefreshTokenService = (IUserRefreshTokenService) ServiceLocator
					.find(IUserRefreshTokenService.class);
			UserRefreshTokenVO tokenVO = userRefreshTokenService.getVOByUserId(userId);
			if (tokenVO == null) {
				appOpenAggVO.setIs_haspower(UFBoolean.FALSE);
				appOpenAggVO.setHint_message(
						NCLangRes4VoTransl.getNCLangRes().getStrByID("100001baseapp_0", "0100001baseapp-0140"));
				return;
			}

			String token = provider.genLoginToken(tokenVO.getThird_token());
			JSONObject tokenMap = JSON.parseObject(token);
			String pageUrl;
			if (appCode.startsWith("60")) {
				appCode = this.getPageUrl(appCode);
			} else if (appCode.startsWith("49")) {
				pageUrl = this.getPageUrl(appCode);
				appOpenAggVO.setPageurl(YhtLoginUtil.genUrl(pageUrl + "?tenantId=" + tenantId));
				return;
			}

			pageUrl = yhtLoginUrl + tokenMap.getString("loginTOken") + diworkLoginUrl + tenantId + paramUrl + serviceUrl
					+ appCode;
			appOpenAggVO.setPageurl(pageUrl);
		} catch (BusinessException var26) {
			YhtUtil.bindLog("bind yht system error", var26);
			appOpenAggVO.setHint_message(
					NCLangRes4VoTransl.getNCLangRes().getStrByID("100001baseapp_0", "0100001baseapp-0137")
							+ var26.getMessage());
		} catch (UnsupportedEncodingException var27) {
			YhtUtil.bindLog("bind yht system error", var27);
			appOpenAggVO.setHint_message(
					NCLangRes4VoTransl.getNCLangRes().getStrByID("100001baseapp_0", "0100001baseapp-0137")
							+ var27.getMessage());
		}

	}

	private String getPageUrl(String appCode) {
		String[] needFields = new String[]{"pageurl"};
		AppPageVO[] appPageVOs = ((IAppPage) ServiceLocator.find(IAppPage.class)).queryAppPagesByAppCodes(needFields,
				new String[]{appCode});
		if (ArrayUtils.isNotEmpty(appPageVOs)) {
			appCode = appPageVOs[0].getPageurl();
		}

		return appCode;
	}
}